<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\kuaishou\schema;

use app\command\BaseWork;
use app\enum\ConfigEnum;
use app\enum\KuaiShouEnum;
use app\service\batch\KuaiShouBatchService;
use think\console\Input;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;

class InitSchemaVideoWork extends BaseWork
{
    public const REDIS_TASK_KEY = ConfigEnum::CACHE_CONFIG[KuaiShouEnum::BATCH_CONFIG_KEY]['batch_schema_video'];

    protected function configure()
    {
        // 指令配置
        $this->setName('init_schema_video_work');

        // 设置描述
        $this->setDescription('视频直达链接初始化');
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $this->getOutputMessage('视频直达链接初始化出队开始');

        $redis = Cache::store('redis')->handler();
        $redisKey = self::REDIS_TASK_KEY;
        // 超过5min就停止
        $t = time();
        $runTime = 5 * 60;
        while (time() - $t <= $runTime) {
            $idStr = $redis->lpop($redisKey);
            if (! $idStr) {
                $this->getOutputMessage('暂无数据');
                sleep(rand(5, 10));
                continue;
            }

            $arr = explode('|||', $idStr);
            $advId = $arr[0];
            $objectId = $arr[1];
            try {
                $this->getOutputMessage('同步[adv_id:' . $advId . ',object_id:' . $objectId . ']开始');
                if (! KuaiShouBatchService::batchSchemaVideo($advId, $objectId)) {
                    $this->getOutputMessage(KuaiShouBatchService::getError(0));
                }
                $this->getOutputMessage('同步[adv_id:' . $advId . ',object_id:' . $objectId . ']完成');
            } catch (\Exception $e) {
                $this->getOutputMessage($e->getMessage());
                $this->getOutputMessage($e->getFile() . '[' . $e->getLine() . ']');
                $this->getOutputMessage($e->getTraceAsString());
            }
        }

        $this->getOutputMessage('视频直达链接初始化出队结束');
    }
}
